import { UserEntity } from '@/api/create/interface'
import { fetchGetStyleById } from '@/api/create/tvwall'
import Alert from '@/components/Alert'
import { t } from 'i18next'
import { useBasicInfoStore } from '../basicInfo/store'
import { useMeetingParamsStore } from '../meetingParams/store'
import { useUserAllStore } from '../user/all/store'
import { CashSourceEntity, MeetingOrTemplateInterfaceTwallInfo, StyleInfoEntity } from './interface'
import { useMeetingTVWallStore } from './store'
import { Poll } from './TvwallPoll'
// import { Poll, Vmp } from './interface'

/**切换画面合成开关*/
export const changeEnable = () => {
	// const { meetingType } = useMeetingParamsStore.getState()
	// useMeetingTVWallStore.setState({ enable: enable })
	// if (enable && meetingType === 0) {
	// 	useMeetingTVWallStore.setState({ broadcast: 1 })
	// }
}
/**切换模式*/
export const changeMode = (_mode: 1 | 2) => {
	const { update, setOperteUsedStyleMap, correct_style } = useMeetingTVWallStore.getState()
	/**设置当前风格选中的模式的缓存*/
	setOperteUsedStyleMap(correct_style, { mode: _mode })
	if (_mode === 2) {
		/**当切换到批量轮询的时候才会重置批量轮询列表*/
		addAllMtToBatchPoll()
	}
	/**更改模式*/
	update({ mode: _mode })
}
/**切换之后*/
export const setAutotype = () => {
	// const { superMtNum } = useBasicInfoStore.getState()
	// const tree = useUserAllStore.getState().tree
	// if (value === 2) {
	// } else if (value === 1) {
	// 	useMeetingVmpStore.setState({ layout: layout ?? 0 })
	// } else if (value === 4 || value === 3) {
	// 	let list = tree
	// 		.filter((x) => x.mcc.account_type !== 10 && (superMtNum ? x.mcc.interactive_mt === 1 : true))
	// 		.map((user) => ({
	// 			account: user.mcc.account,
	// 			account_type: user.mcc.account_type,
	// 			name: user.mcc.name,
	// 			parentId: '',
	// 		}))
	// 	useMeetingVmpStore.setState({ layout: layout ?? 0 })
	// 	useMeetingVmpStore.getState().setBatchPollParams({ members: list })
	// } else {
	// 	return false
	// }
}
/**根据类型获取对应名称*/
export const getTvWallTypeName = (type: number) => {
	var _name = ''
	switch (type) {
		case 2:
			_name = t('发言方跟随')
			break
		case 3:
			_name = t('管理方跟随')
			break
		case 4:
			_name = t('会议轮询跟随')
			break
		case 10:
			_name = t('内容共享跟随')
			break
		case 6:
			_name = t('选看画面合成')
			break
		case 5:
			_name = t('单通道轮询')
			break
		case 8:
			_name = t('自主多画面')
			break
		case 9:
			_name = t('开启四分屏')
			break
		case 7:
			_name = t('批量轮询')
			break
		case 11:
			_name = t('会议广播跟随')
			break
	}
	return _name
}
/**悬浮提示框内容*/
export const handleGetErrorTipText = (type: number) => {
	let text = ''
	switch (type) {
		case 1:
			text = t('HDU不在线!')
			break
		case 2:
			text = t('尚未配置任何电视墙通道，请联系管理员!')
			break
		case 3:
			text = t('其他会议正在使用此通道!')
			break
		case 4:
			text = t('网络超时!')
			break
		case 255:
			text = t('此通道不可用!')
			break
		default:
			text = ''
			break
	}
	return text
}
export const initOneTvwall = async (styleInfo: StyleInfoEntity | null) => {
	const { update, used_style_map } = useMeetingTVWallStore.getState()
	if (styleInfo) {
		const { batch_poll, style_id, mode = 1, show_mt_name } = styleInfo
		/**设置选中的风格*/
		const res = await fetchGetStyleById(style_id)
		if (res.success) {
			update({ correct_style_positions: res.details ?? [] })
		} else {
			const result = used_style_map.find((item) => {
				return item.id === style_id
			})?.positions
			update({ correct_style_positions: result ?? [] })
		}
		update({
			correct_style: style_id,
			show_mt_name: show_mt_name ?? 0,
			mode: mode,
		})
		initPollData(batch_poll ?? null)
	}
}
/**新增所有的终端进入批量轮询*/
export const addAllMtToBatchPoll = () => {
	const { update, correct_style, operate_correct_style_info } = useMeetingTVWallStore.getState()
	const { superMtNum } = useBasicInfoStore.getState()
	const tree = useUserAllStore.getState().tree
	let list = tree
		.filter((x) => x.mcc.account_type !== 10 && (superMtNum ? x.mcc.interactive_mt === 1 : true))
		.map((user) => ({
			account: user.mcc.account,
			account_type: user.mcc.account_type,
			name: user.mcc.name,
			parentId: '',
		}))
	/**更新批量轮询终端 */

	/**更新当前风格id批量轮询终端缓存 */
	let batch_poll = Object.assign({}, operate_correct_style_info[correct_style].batch_poll, { members: list })
	let result = Object.assign({}, operate_correct_style_info[correct_style], { batch_poll: batch_poll })
	operate_correct_style_info[correct_style] = result
	update({
		pollMembers: list,
		operate_correct_style_info: operate_correct_style_info,
	})
}
export const initPollData = (data: Poll | null) => {
	const { pollPlanOptions, update } = useMeetingTVWallStore.getState()
	if (data) {
		let _name = data.name ?? ''
		let _keep_time = data.keep_time ?? 30
		let _num = data.num ?? 0
		if (_keep_time !== 15 && _keep_time !== 30 && _keep_time !== 60) {
			update({
				pollIntervalOptionsVal: 0,
				pollInterval: String(_keep_time),
				pollPlanValue: pollPlanOptions.find((item) => item.label === _name)?.value ?? '0',
				pollTimes: _num === 0 ? '' : String(_num),
				unlimited: _num === 0,
				pollPlanName: _name,
				pollMembers: data.members,
			})
		} else {
			update({
				pollIntervalOptionsVal: _keep_time,
				pollInterval: '5',
				pollPlanValue: pollPlanOptions.find((item) => item.label === _name)?.value ?? '0',
				pollTimes: _num === 0 ? '' : String(_num),
				unlimited: _num === 0,
				pollPlanName: _name,
				pollMembers: data.members,
			})
		}
	} else {
		const { superMtNum } = useBasicInfoStore.getState()
		const tree = useUserAllStore.getState().tree
		let list = tree
			.filter((x) => x.mcc.account_type !== 10 && (superMtNum ? x.mcc.interactive_mt === 1 : true))
			.map((user) => ({
				account: user.mcc.account,
				account_type: user.mcc.account_type,
				name: user.mcc.name,
				parentId: '',
			}))
		update({
			pollPlanValue: '0',
			pollInterval: '30',
			pollIntervalOptionsVal: 30,
			unlimited: true,
			pollTimes: '0',
			pollMembers: list,
		})
	}
}
export const getPollParams = () => {
	const { pollPlanValue, pollPlanOptions, pollIntervalOptionsVal, pollInterval, unlimited, pollMembers, pollTimes } =
		useMeetingTVWallStore.getState()
	return {
		id: '',
		mode: 1,
		name: pollPlanValue === '0' ? '' : pollPlanOptions.find((item) => item.value === pollPlanValue)?.label ?? '',
		keep_time: pollIntervalOptionsVal !== 0 ? pollIntervalOptionsVal : Number(pollInterval),
		num: unlimited ? 0 : Number(pollTimes),
		members: pollMembers.map((item) => {
			return {
				account: item.account,
				account_type: item.account_type,
				name: item.name,
				parent_id: item.parent_id,
			}
		}),
	}
}
/**在第一次进入会管的时候/切换预案*/
export const setInitCashData = (_d: MeetingOrTemplateInterfaceTwallInfo | null) => {
	if (!_d) return
	let { isNeedUpdate, update } = useMeetingTVWallStore.getState()
	let tvwalls = _d.tvwalls
	let cashData: { [key: string]: Partial<CashSourceEntity> } = {}
	tvwalls?.forEach((item) => {
		let value: CashSourceEntity = {
			mode: item.mode ?? 1,
			show_mt_name: item.show_mt_name ?? 0,
			style_id: item.style_id ?? '',
			members: item.members ?? [],
			batch_poll: item.batch_poll ?? null,
		}
		cashData[item.style_id] = value
	})
	/**过滤掉不属于当前会议操作sfu和传统支持四分屏不支持自主多画面  端口不支持四分屏支持自主多画面*/
	for (let key in cashData) {
		let current = cashData[key]
		let result: any = []
		const meetingType = useMeetingParamsStore.getState().meetingType
		if (current.mode === 1) {
			current.members?.forEach((item) => {
				if (
					(meetingType === 1 && item.member_type === 9) ||
					((meetingType === 0 || meetingType === 2) && item.member_type === 8)
				) {
				} else {
					result.push(item)
				}
			})
			cashData[key].members = result
		}
		if (current.mode === 2) {
			cashData[key].batch_poll = current.batch_poll
		}
	}
	update({ operate_correct_style_info: cashData ?? {}, isNeedUpdate: !isNeedUpdate })
}
/**刷新电视墙成员数据 */
export const refreshTvwallMembers = () => {
	setTimeout(() => {
		let { operate_correct_style_info: cashData, update } = useMeetingTVWallStore.getState()
		const meetingType = useMeetingParamsStore.getState().meetingType
		const tree = useUserAllStore.getState().tree
		const uuids = tree.map((x) => x.uuid)
		for (let key in cashData) {
			let current = cashData[key]
			let result: any = []
			if (current.mode === 1) {
				current.members?.forEach((item) => {
					if (item.member_type === 1) {
						if (uuids.includes(`${item.account_type}$$${item.account}`)) {
							result.push(item)
						}
					} else if (
						(meetingType === 1 && item.member_type === 9) ||
						((meetingType === 0 || meetingType === 2) && item.member_type === 8)
					) {
					} else {
						result.push(item)
					}
				})
				cashData[key].members = result
			}
			if (current.mode === 2) {
				let pollMembers = current.batch_poll?.members
				if (current.batch_poll && pollMembers) {
					pollMembers = pollMembers?.filter((value) => {
						return uuids.includes(`${value.account_type}$$${value.account}`)
					})
					current.batch_poll.members = pollMembers
					cashData[key].batch_poll = current.batch_poll
				}
			}
		}
		update({ operate_correct_style_info: cashData })
	}, 500)
}
/**切换空预案*/
export const clearCashData = () => {
	const isNeedUpdate = useMeetingTVWallStore.getState().isNeedUpdate
	useMeetingTVWallStore.getState().update({
		correct_style: '',
		operate_correct_style_info: {},
		used_style_map: [],
		correct_style_operate_box_info: '',
		correct_style_positions: [],
		isNeedUpdate: !isNeedUpdate,
		mode: 1,
		show_mt_name: 1,
	})
}
/**设置批量轮询列表的缓存（从与会方列表批量添加）*/
export const setBatchPollMemeberCash = (data: Array<UserEntity>) => {
	let { operate_correct_style_info, correct_style: id, update } = useMeetingTVWallStore.getState()
	let source = {}
	let _batch_poll = operate_correct_style_info[id].batch_poll
	if (data && _batch_poll) {
		/**找到当前通道对应的盒子*/
		_batch_poll.members = data
		source = Object.assign({}, operate_correct_style_info[id], { batch_poll: _batch_poll })
	}
	operate_correct_style_info[id] = source
	update({ operate_correct_style_info: operate_correct_style_info })
}
/**
 * 根据切换会议类型(清空缓存)针对于端口会议和传统会议
 * 清空缓存当中的四分屏数据
 *针对于RTC会议清空画面合成数据
 */
export const setCashDataByMeetingType = () => {
	let { isNeedUpdate } = useMeetingTVWallStore.getState()
	const meetingType = useMeetingParamsStore.getState().meetingType
	let source = useMeetingTVWallStore.getState().operate_correct_style_info
	for (let key in source) {
		let target = source[key].members
		if (target) {
			for (let j = 0; j < target.length; j++) {
				let current = target[j]
				let member_type = target[j].member_type
				if (meetingType === 0 || meetingType === 1) {
					/**清空四分屏*/
					if (member_type === 9) {
						current = {
							member_type: 0,
							hdu_alias: current.hdu_alias,
							hdu_id: current.hdu_id,
						}
					}
				}
				if (meetingType === 2) {
					/**清空vmp画面合成*/
					if (member_type === 8) {
						current = {
							member_type: 0,
							hdu_alias: current.hdu_alias,
							hdu_id: current.hdu_id,
						}
					}
				}
				target[j] = current
			}
		}
		source[key].members = target
	}
	useMeetingTVWallStore.getState().update({ operate_correct_style_info: source ?? [], isNeedUpdate: !isNeedUpdate })
}
/**获取画面合成预案保存数据参数*/
export const getTvwallPlanParam = () => {
	const { show_mt_name, enable, used_style_map, operate_correct_style_info } = useMeetingTVWallStore.getState()
	/**获取电视墙预案对象*/
	if (!enable) return null
	if (!checkTvwallData()) return null
	/**遍历缓存数据*/
	let params = used_style_map.map((item) => {
		/**获取风格id */
		let style_id = item.id
		/**获取对应风格的缓存数据*/
		let cashData = operate_correct_style_info[style_id] ?? {}
		let mode = cashData.mode ?? 1
		if (mode === 2) {
			return {
				mode: cashData.mode ?? 2,
				style_id: style_id,
				show_mt_name: show_mt_name,
				batch_poll: cashData.batch_poll ?? null,
				members: null,
			}
		} else {
			const _members = cashData.members?.map((item) => {
				if (item.member_type === 5 && item.poll) {
					item.poll.members = item.poll.members.map((value) => {
						return Object.assign({}, value, { conf_e164: value['conf_e164'] || value['parent_id'] })
					})
				}
				return item
			})
			return {
				mode: cashData.mode ?? 1,
				style_id: style_id,
				show_mt_name: show_mt_name ?? 0,
				batch_poll: null,
				members:
					_members?.filter((item) => {
						return item.member_type && item.member_type !== 0
					}) ?? [],
			}
		}
	})
	return {
		tvwalls: params,
	}
}
export const getTvwallParam = () => {
	/**例会的预案列表隐藏所以创会的参数下参为空串*/
	const repeat = useBasicInfoStore.getState().repeat
	let { planOptions, tvwallPlanValue, enable } = useMeetingTVWallStore.getState()
	if (!enable) {
		return null
	}
	let item = planOptions.find((item) => item.value === tvwallPlanValue)
	const _params = getTvwallPlanParam()
	let params = Object.assign({}, _params, { name: repeat ? '' : item?.value !== '0' ? item?.label : '' })
	return params
}
/**检查电视墙数据 */
export const checkTvwallData = () => {
	const { used_style_map, operate_correct_style_info, enable } = useMeetingTVWallStore.getState()
	if (!enable) return true
	let flag = true
	if (used_style_map.length === 0) {
		Alert(t('请选择电视墙风格'))
		flag = false
	}
	for (let i = 0; i < used_style_map.length; i++) {
		/**获取风格id */
		let style_id = used_style_map[i].id
		/**获取对应风格的缓存数据*/
		let cashData = operate_correct_style_info[style_id] ?? {}
		let mode = cashData.mode ?? 1
		if (mode === 2) {
			// 证明此分格对应的是批量轮询
			if (cashData.batch_poll?.keep_time === -1) {
				Alert(t('请设置轮询间隔'))
				flag = false
				break
			} else if (Number(cashData.batch_poll?.keep_time) < 5 || Number(cashData.batch_poll?.keep_time) > 7200) {
				Alert(t('轮询间隔应为5~7200秒'))
				flag = false
				break
			}
			if (cashData.batch_poll?.num === -1) {
				Alert(t('请设置轮询次数'))
				flag = false
				break
			} else if (
				Number(cashData.batch_poll?.num) !== 0 &&
				(Number(cashData.batch_poll?.num) < 1 || Number(cashData.batch_poll?.num) > 9999)
			) {
				Alert(t('轮询次数应为1~9999次'))
				flag = false
				break
			}
			if (cashData.batch_poll?.members && cashData.batch_poll?.members.length === 0) {
				Alert(t('电视墙批量轮询列表不能为空'))
				flag = false
				break
			}
		}
	}
	return flag
}
